package com.example.layui.controller;

import com.example.layui.mapper.RoleMapper;
import com.example.layui.mapper.UserMapper;
import com.example.layui.pojo.Bar;
import com.example.layui.pojo.Role;
import com.example.layui.pojo.User;
import com.example.layui.pojo.UserVo;
import com.example.layui.service.MenuService;
import com.example.layui.util.ResponseResult;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Controller
public class UserController {

    @Resource
    private UserMapper userMapper;

    @Resource
    private MenuService menuService;

    @Resource
    private RoleMapper roleMapper;

    @Resource
    PasswordEncoder passwordEncoder;



    @RequestMapping(value = {"/index", "/"})
    public String index(Model model) {
        List<Bar> bars = menuService.queryBars();
        model.addAttribute("bars", bars);
        return "views/index";
    }


    @RequestMapping("/demo/table/user/")
    @ResponseBody
    public ResponseResult users(UserVo user, Integer page, Integer limit) {
        ResponseResult responseResult = new ResponseResult(0, ""
                , userMapper.count(user)
                , userMapper.queryByPage(user, (page - 1) * limit, limit));
        return responseResult;
    }


    @RequestMapping("/user/user/userform.html")
    public String userform(Model model) {
        List<Role> roles = roleMapper.queryAllRole();
        model.addAttribute("roles", roles);
        return "views/user/user/userform";
    }


    @RequestMapping("/delete")
    @ResponseBody
    public ResponseResult delete(@RequestBody List<UserVo> userList) {
        for (UserVo user : userList) {
            //删除用户关联的user_role表数据
            userMapper.delRoleByUid(user.getId());
            //删除用户
            userMapper.delete(user.getId());
        }
        ResponseResult responseResult = new ResponseResult(0, "", "");
        return responseResult;
    }

    @RequestMapping("/deleteById")
    @ResponseBody
    public ResponseResult deleteById(int id) {
        //删除用户关联的user_role表数据
        userMapper.delRoleByUid(id);
        //删除用户
        userMapper.delete(id);
        ResponseResult responseResult = new ResponseResult(0, "", "");
        return responseResult;
    }

    @RequestMapping("/add")
    @ResponseBody
    public ResponseResult add(String name, String password,String phone,String address, int[] roles, String enabled, String locked) {
        //获取security登陆的用户
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //实例化一个要添加的对象
        UserVo userVo = new UserVo();
        userVo.setName(name);
        userVo.setPassword(passwordEncoder.encode(password));
        userVo.setPhone(phone);
        userVo.setAddress(address);
        userVo.setCreateby(user.getId());
        userVo.setCreationDate(new Date(System.currentTimeMillis()));
        if (enabled.equals("on")) {
            userVo.setEnabled(true);
        } else {
            userVo.setEnabled(false);
        }
        if (locked.equals("on")) {
            userVo.setLocked(true);
        } else {
            userVo.setLocked(false);
        }
        int result = userMapper.addUser(userVo);
        ResponseResult responseResult = null;
        if (result > 0) {
            User user2 = userMapper.queryByName(userVo.getName());
            for (int rid : roles) {
                userMapper.addRole(user2.getId(), rid);
            }
            responseResult = new ResponseResult(0, "添加成功", "");
        } else {
            responseResult = new ResponseResult(0, "添加失败", "");
        }

        return responseResult;
    }


    @RequestMapping("/user/user/update")
    public String update(int id, Model model) {
        UserVo user = userMapper.queryById(id);
        user.setRoles(userMapper.getRolesById(id));
        List<Integer> roleIdList = new ArrayList<>();
        for (Role role : user.getRoles()) {
            roleIdList.add(role.getId());
        }
        List<Role> roles = roleMapper.queryAllRole();
        model.addAttribute("roles", roles);
        model.addAttribute("user", user);
        model.addAttribute("roleIdList", roleIdList);
        return "views/user/user/userform2";
    }

    @RequestMapping("/doupdate")
    @ResponseBody
    public ResponseResult doupdate(int id, String name, String password,String phone,String address, int[] roles, String enabled, String locked) {
        //获取security登陆的用户
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //实例化一个要添加的对象
        UserVo userVo = new UserVo();
        userVo.setId(id);
        userVo.setName(name);
        userVo.setPhone(phone);
        userVo.setAddress(address);
        userVo.setModifyby(user.getId());
        userVo.setModifyDate(new Date(System.currentTimeMillis()));
        //加密密码
        if (password.length() <= 12 && password.length() >= 6) {
            userVo.setPassword(passwordEncoder.encode(password));
        } else {
            userVo.setPassword(password);
        }
        if (enabled.equals("on")) {
            userVo.setEnabled(true);
        } else {
            userVo.setEnabled(false);
        }
        if (locked.equals("on")) {
            userVo.setLocked(true);
        } else {
            userVo.setLocked(false);
        }
        int result = userMapper.update(userVo);
        ResponseResult responseResult = null;
        if (result > 0) {
            //rolesList 原来user的role列表 oldRoleIdList 原来user的roleid列表
            // roles 提交的user的roleid数组
            List<Role> rolesList = userMapper.getRolesById(id);
            List<Integer> oldRoleIdList = new ArrayList<>();
            for (Role role : rolesList) {
                oldRoleIdList.add(role.getId());
            }
            List<Integer> newRoleIdList =new ArrayList<>();
            for (int i = 0; i < roles.length; i++) {
                newRoleIdList.add(roles[i]);
            }
            for(int rid : newRoleIdList){
                if(!oldRoleIdList.contains(rid)){
                    //新增操作 - user_role表
                    userMapper.addRole(id,rid);
                }
            }
            for(int rid : oldRoleIdList){
                if(!newRoleIdList.contains(rid)){
                    //删除操作 - user_role表
                    userMapper.delRole(id,rid);
                }
            }
            responseResult = new ResponseResult(0, "修改成功", "");
        } else {
            responseResult = new ResponseResult(0, "修改失败", "");
        }
        return responseResult;
    }

    @RequestMapping("/click")
    @ResponseBody
    public ResponseResult enabled(int id, String name, boolean checked) {
        userMapper.updateByLock(id, name, checked);
        return new ResponseResult(0, "", "");
    }

}

